const path = require('path');
const dotenv = require('dotenv');
const fs = require('fs');

class EnvironmentLoader {
    constructor() {
        this.env = process.env.NODE_ENV || 'development';
        this.projectRoot = path.resolve(__dirname, '../../');
        this.loadEnvironmentConfig();
    }

    loadEnvironmentConfig() {
        // 加载基础 .env 文件
        const baseEnvPath = path.join(this.projectRoot, '.env');
        if (fs.existsSync(baseEnvPath)) {
            dotenv.config({ path: baseEnvPath });
            console.log('✅ 加载基础环境配置');
        }

        // 根据 NODE_ENV 加载对应的环境配置文件
        const envFilePath = path.join(this.projectRoot, `.env.${this.env}`);
        if (fs.existsSync(envFilePath)) {
            dotenv.config({ path: envFilePath, override: true });
            console.log(`✅ 加载 ${this.env} 环境配置`);
        } else {
            console.log(`⚠️  未找到 ${this.env} 环境配置文件: ${envFilePath}`);
        }

        // 验证必要的环境变量
        this.validateRequiredEnvVars();
    }

    validateRequiredEnvVars() {
        const requiredVars = [
            'NODE_ENV',
            'PORT',
            'DB_HOST',
            'DB_PORT',
            'DB_NAME',
            'DB_USERNAME',
            'DB_PASSWORD',
            'JWT_SECRET',
            'REDIS_HOST',
            'REDIS_PORT'
        ];

        const missingVars = requiredVars.filter(varName => !process.env[varName]);

        if (missingVars.length > 0) {
            console.error('❌ 缺少必要的环境变量:', missingVars.join(', '));
            console.error('💡 请检查环境配置文件是否正确设置');
            process.exit(1);
        }
    }

    get(key, defaultValue = null) {
        return process.env[key] || defaultValue;
    }

    getInt(key, defaultValue = 0) {
        const value = this.get(key, defaultValue);
        return parseInt(value, 10);
    }

    getBoolean(key, defaultValue = false) {
        const value = this.get(key, defaultValue);
        return value === 'true' || value === '1' || value === true;
    }

    getFloat(key, defaultValue = 0) {
        const value = this.get(key, defaultValue);
        return parseFloat(value);
    }

    // 获取数据库配置
    getDatabaseConfig() {
        return {
            host: this.get('DB_HOST'),
            port: this.getInt('DB_PORT'),
            database: this.get('DB_NAME'),
            username: this.get('DB_USERNAME'),
            password: this.get('DB_PASSWORD'),
            dialect: 'mysql',
            logging: this.getBoolean('DEBUG', false),
            timezone: '+08:00'
        };
    }

    // 获取 Redis 配置
    getRedisConfig() {
        return {
            host: this.get('REDIS_HOST'),
            port: this.getInt('REDIS_PORT'),
            password: this.get('REDIS_PASSWORD'),
            db: this.getInt('REDIS_DB', 0)
        };
    }

    // 获取 OKX API 配置
    getOkxConfig() {
        return {
            apiKey: this.get('OKX_API_KEY'),
            secretKey: this.get('OKX_SECRET_KEY'),
            passphrase: this.get('OKX_PASSPHRASE'),
            sandbox: this.getBoolean('OKX_SANDBOX', false)
        };
    }

    // 获取邮件配置
    getMailConfig() {
        return {
            host: this.get('SMTP_HOST'),
            port: this.getInt('SMTP_PORT'),
            user: this.get('SMTP_USER'),
            pass: this.get('SMTP_PASS'),
            from: this.get('SMTP_FROM')
        };
    }

    // 获取安全配置
    getSecurityConfig() {
        return {
            jwtSecret: this.get('JWT_SECRET'),
            jwtExpiresIn: this.get('JWT_EXPIRES_IN', '24h'),
            bcryptRounds: this.getInt('BCRYPT_ROUNDS', 10),
            sessionSecret: this.get('SESSION_SECRET'),
            cookieSecret: this.get('COOKIE_SECRET')
        };
    }

    // 获取应用配置
    getAppConfig() {
        return {
            port: this.getInt('PORT', 3000),
            nodeEnv: this.get('NODE_ENV', 'development'),
            debug: this.getBoolean('DEBUG', false),
            corsOrigin: this.get('CORS_ORIGIN', 'http://localhost:3000')
        };
    }

    // 获取日志配置
    getLogConfig() {
        return {
            level: this.get('LOG_LEVEL', 'info'),
            file: this.get('LOG_FILE', 'logs/app.log')
        };
    }

    // 获取文件上传配置
    getUploadConfig() {
        return {
            path: this.get('UPLOAD_PATH', 'uploads'),
            maxFileSize: this.getInt('MAX_FILE_SIZE', 5242880)
        };
    }

    // 获取通知配置
    getNotificationConfig() {
        return {
            webhookUrl: this.get('WEBHOOK_URL'),
            slackWebhook: this.get('SLACK_WEBHOOK'),
            discordWebhook: this.get('DISCORD_WEBHOOK')
        };
    }

    // 获取管理员账户配置
    getAdminConfig() {
        return {
            username: this.get('ADMIN_USERNAME', 'admin'),
            email: this.get('ADMIN_EMAIL', 'admin@okx-robot.com'),
            password: this.get('ADMIN_PASSWORD', 'admin123'),
            role: this.get('ADMIN_ROLE', 'admin')
        };
    }

    // 检查是否为开发环境
    isDevelopment() {
        return this.env === 'development';
    }

    // 检查是否为生产环境
    isProduction() {
        return this.env === 'production';
    }

    // 检查是否为测试环境
    isTest() {
        return this.env === 'test';
    }

    // 打印当前环境信息
    printEnvironmentInfo() {
        console.log('🌍 环境信息:');
        console.log(`   环境: ${this.env}`);
        console.log(`   端口: ${this.get('PORT', 3000)}`);
        console.log(`   数据库: ${this.get('DB_NAME')}`);
        console.log(`   Redis: ${this.get('REDIS_HOST')}:${this.get('REDIS_PORT')}`);
        console.log(`   调试模式: ${this.getBoolean('DEBUG', false)}`);
        console.log('');
    }
}

// 创建全局实例
const envLoader = new EnvironmentLoader();

module.exports = envLoader;
